import React,{ useState, useEffect, useRef, useCallback } from 'react'
import Taro, { useDidHide, useDidShow } from '@tarojs/taro'
import { request } from '@/utils'
import { View, Image, Text } from '@tarojs/components'
import { AtList, AtListItem, AtButton } from "taro-ui"
import { ALLTABS } from '@/config'

import './index.less'



const Refuel = () => {
  const [oil, setOil] = useState('-')
  const [src, setSrc] = useState('')
  const [role, setRole] = useState('')
  const [ time, setTime] = useState(0)
  const [ number, setNumber] = useState('')
  const [ price, setPrice] = useState(0)
  const [complete, setComplete] = useState(false)
  const timer = useRef(null)
  const timeOut = useRef(null)
  const getOil = async () => {
    Taro.showLoading({mask: true})
    const {authUser, error} = await request({url: 'hkshihua/user/getAllprofile'})
    if(error) return
    setOil(authUser.oilRemain)
    setRole(authUser.role)
  }
  const getInfo = useCallback(async (e) => {
    const {error, num, totalPrice} = await request({ url: 'hkshihua/motorcade/getIsPayInfo', data: {userPayCode: e}, flag: true})
    if(error) {
      clearInterval(timer.current)
      clearTimeout(timeOut.current)
      setComplete(true)
      setNumber(num)
      setPrice(totalPrice)
      getOil()
    }
  }, [])

  const createQrCode = useCallback(async () => {
    setTime(60)
    clearInterval(timer.current)
    Taro.showLoading({mask: true})
    const {qrcode, userPayCode, error} = await request({ url: 'hkshihua/motorcade/qr/code'})
    if(error) return
    setSrc(qrcode) 
    timer.current = setInterval(() => {
      getInfo(userPayCode)
    }, 2000)
  }, [getInfo])
 
  useDidShow(async () => {
    await getOil()
    await createQrCode()
    Taro.getCurrentPages()[0].getTabBar().setData({
      selected: 1
    })   
    
  })
  useDidHide(() => {
    clearInterval(timer.current)
    clearTimeout(timeOut.current)
    setComplete(false)
  })
  useEffect(() => {
    Taro.getCurrentPages()[0].getTabBar().setData({
      list: ALLTABS[role]
    })
    timeOut.current = setTimeout(() => {
      setTime(time - 1)
      if(time <= 0) {
        createQrCode()
      }
    }, 1000)
    return () => {
      clearTimeout(timeOut.current)
    }
  }, [createQrCode, role, time])
  const handleClick = () => {
    if(complete) return
    Taro.previewImage({
      urls: [src]
    })
  }
  const handleBack = () => {
    Taro.switchTab({ url: '/pages/index/index'})
  }
  return <View className='refuel'>
    <AtList>
      <AtListItem title='剩余油量：' extraText={`${oil || 0}升`}  />
    </AtList>
    <View className='content'>
      <View>扫码加油</View>
      <Image src={src} onClick={handleClick} height={!complete ? '50%' : '100%'} />
      {!complete && <View onClick={createQrCode}>刷新<Text style={{color: '#ddd'}}> ({time}秒)</Text></View>}
      {complete && (
        <View className='complete'>
          <View style={{marginTop: '20px'}}>支付成功</View>
          <View style={{marginTop: '10px', color: '#999'}}>
            <Text style={{marginRight: '10px'}}>加油量：{number}</Text>
            <Text>金额：{price}</Text>
            <View style={{ marginTop: '20px'}}>
              <AtButton type='default' onClick={handleBack}>确定</AtButton>
            </View>
          </View>
        </View>
      )}
    </View>
  </View>
}

export default Refuel